/**
 * 听写模式管理
 * 包括：单词模式、驼峰模式、填空模式
 */

class DictationManager {
    constructor() {
        this.words = [];
        this.currentIndex = 0;
        this.mode = 'camelCase'; // word, camelCase, fillIn
        this.results = [];
        this.sessionStartTime = null;
        this.currentWordStartTime = null;
        this.enableNextOnEnter = false;
        this.nextTimer = null;
        
        console.log('✍️ 听写管理器已加载');
    }

    /**
     * 开始听写
     */
    start(words, mode = 'camelCase') {
        if (!words || words.length === 0) {
            alert('没有可用的单词');
            return;
        }

        this.words = words;
        this.currentIndex = 0;
        this.mode = mode;
        this.results = [];
        this.sessionStartTime = Date.now();

        console.log(`开始听写 ${this.words.length} 个单词，模式: ${mode}`);
        
        // 显示模式选择（如果还没选择）
        this.showModeSelection();
    }

    /**
     * 显示模式选择
     */
    showModeSelection() {
        const container = document.querySelector('.dictation-container');
        if (!container) return;

        container.innerHTML = `
            <div class="mode-selection-card animate-fadeIn">
                <h2>选择听写模式</h2>
                <p class="mode-subtitle">请选择适合的听写方式</p>

                <div class="dictation-modes">
                    <div class="dictation-mode-card ${this.mode === 'word' ? 'active' : ''}" data-mode="word">
                        <div class="mode-icon">📝</div>
                        <h3>单词模式</h3>
                        <p>听音频，完整拼写单词</p>
                        <div class="mode-difficulty">难度: ⭐⭐⭐⭐</div>
                    </div>

                    <div class="dictation-mode-card ${this.mode === 'camelCase' ? 'active' : ''}" data-mode="camelCase">
                        <div class="mode-icon">🔥</div>
                        <h3>驼峰命名模式</h3>
                        <p>分词播放，输入驼峰格式</p>
                        <div class="mode-difficulty">难度: ⭐⭐⭐⭐</div>
                        <div class="mode-badge">推荐</div>
                    </div>

                    <div class="dictation-mode-card ${this.mode === 'fillIn' ? 'active' : ''}" data-mode="fillIn">
                        <div class="mode-icon">📋</div>
                        <h3>填空模式</h3>
                        <p>显示部分字母，补充完整</p>
                        <div class="mode-difficulty">难度: ⭐⭐⭐</div>
                    </div>
                </div>

                <button class="btn btn-primary btn-large" id="btn-confirm-mode">
                    开始听写
                </button>
            </div>
        `;

        // 绑定模式选择
        const modeCards = document.querySelectorAll('.dictation-mode-card');
        modeCards.forEach(card => {
            card.addEventListener('click', () => {
                modeCards.forEach(c => c.classList.remove('active'));
                card.classList.add('active');
                this.mode = card.dataset.mode;
            });
        });

        // 确认按钮
        const confirmBtn = document.getElementById('btn-confirm-mode');
        if (confirmBtn) {
            confirmBtn.addEventListener('click', () => {
                this.currentWordStartTime = Date.now();
                this.render();
            });
        }
    }

    /**
     * 渲染听写界面
     */
    render() {
        const container = document.querySelector('.dictation-container');
        if (!container) return;

        const currentWord = this.words[this.currentIndex];
        this.currentWordStartTime = Date.now();
        this.enableNextOnEnter = false; // 重置回车键状态

        // 更新进度信息
        this.updateProgress();

        // 根据模式渲染不同界面
        if (this.mode === 'fillIn') {
            this.renderFillInMode(currentWord);
        } else {
            this.renderStandardMode(currentWord);
        }

        this.bindEvents();
        
        // 自动播放第一次（捕获可能的错误）
        setTimeout(() => {
            this.playWord().catch(err => {
                console.warn('自动播放失败，可能需要用户交互:', err);
            });
        }, 300);
    }

    /**
     * 播放单词（返回Promise）
     */
    async playWord() {
        const currentWord = this.words[this.currentIndex];
        if (!currentWord || !window.speechManager) {
            console.error('无法播放：currentWord或speechManager不存在');
            return;
        }

        console.log('准备播放单词:', currentWord.word);

        const playBtn = document.getElementById('btn-play-word');
        if (playBtn) {
            playBtn.classList.add('playing');
            setTimeout(() => playBtn.classList.remove('playing'), 500);
        }

        const word = currentWord.word;
        
        try {
            // 判断播放方式
            if ((this.mode === 'camelCase' || this.mode === 'fillIn') && 
                (currentWord.type === '驼峰短语' || currentWord.pronunciation_mode === 'split')) {
                // 驼峰模式/填空模式的驼峰短语：分词播放
                const displayWord = this.formatCamelCase(word);
                console.log('分词播放:', displayWord);
                await speechManager.speakCamelCase(displayWord);
            } else {
                // 单词模式：完整播放
                console.log('完整播放:', word);
                await speechManager.speak(word);
            }
        } catch (error) {
            console.error('播放失败:', error);
        }
    }

    /**
     * 渲染标准模式（单词/驼峰）- 横屏优化
     */
    renderStandardMode(currentWord) {
        const container = document.querySelector('.dictation-container');
        
        const modeText = this.mode === 'camelCase' ? '驼峰命名模式' : '单词模式';
        const hintText = this.mode === 'camelCase' 
            ? `共 ${this.getWordCount(currentWord.word)} 个单词`
            : '请输入完整单词';

        container.innerHTML = `
            <div class="dictation-card-wide animate-fadeIn">
                <div class="dictation-left">
                    <div class="dictation-mode-badge">${modeText}</div>
                    <div class="word-number">第 ${this.currentIndex + 1} 题</div>

                    <div class="play-section-wide">
                        <button class="btn-play-dictation" id="btn-play-word" title="播放发音">
                            <svg viewBox="0 0 24 24" width="48" height="48">
                                <path fill="currentColor" d="M8 5v14l11-7z"/>
                            </svg>
                            <span>播放单词</span>
                        </button>
                        <p class="play-hint">${hintText}</p>
                    </div>

                    <div class="speed-control-wide">
                        <div class="speed-label">语速设置</div>
                        <div class="speed-buttons">
                            <button class="speed-btn ${speechManager.rate === 0.7 ? 'active' : ''}" data-speed="0.7">慢速</button>
                            <button class="speed-btn ${speechManager.rate === 1.0 ? 'active' : ''}" data-speed="1.0">正常</button>
                            <button class="speed-btn ${speechManager.rate === 1.3 ? 'active' : ''}" data-speed="1.3">快速</button>
                        </div>
                    </div>
                </div>

                <div class="dictation-right">
                    <div class="input-section-wide">
                        <label class="input-label">你的答案</label>
                        <input type="text" 
                               class="input-dictation" 
                               id="word-input" 
                               placeholder="请输入你听到的单词"
                               autocomplete="off"
                               autofocus>
                        ${this.mode === 'camelCase' ? '<p class="input-hint">💡 提示: 首字母小写，如 getUserName</p>' : ''}
                    </div>

                    <div class="feedback-area-wide" id="feedback-area"></div>

                    <div class="action-buttons-wide">
                        <button class="btn btn-secondary btn-wide" id="btn-skip">
                            ⏭️ 跳过 <span class="btn-hotkey">Ctrl+S</span>
                        </button>
                        <button class="btn btn-secondary btn-wide" id="btn-show-answer">
                            💡 查看答案 <span class="btn-hotkey">Tab</span>
                        </button>
                        <button class="btn btn-primary btn-wide" id="btn-submit">
                            ✅ 提交 <span class="btn-hotkey">Enter</span>
                        </button>
                    </div>
                </div>
            </div>
        `;
    }

    /**
     * 渲染填空模式 - 横屏优化
     */
    renderFillInMode(currentWord) {
        const container = document.querySelector('.dictation-container');
        const hint = this.generateHint(currentWord.word);

        container.innerHTML = `
            <div class="dictation-card-wide animate-fadeIn">
                <div class="dictation-left">
                    <div class="dictation-mode-badge">填空模式</div>
                    <div class="word-number">第 ${this.currentIndex + 1} 题</div>

                    <div class="play-section-wide">
                        <button class="btn-play-dictation" id="btn-play-word" title="播放发音">
                            <svg viewBox="0 0 24 24" width="48" height="48">
                                <path fill="currentColor" d="M8 5v14l11-7z"/>
                            </svg>
                            <span>播放单词</span>
                        </button>
                    </div>

                    <div class="hint-display-wide">
                        <div class="hint-label">提示字母</div>
                        <div class="hint-letters">${hint}</div>
                        <div class="hint-info">共 ${currentWord.word.replace(/\s/g, '').length} 个字母</div>
                    </div>

                    <div class="speed-control-wide">
                        <div class="speed-label">语速设置</div>
                        <div class="speed-buttons">
                            <button class="speed-btn ${speechManager.rate === 0.7 ? 'active' : ''}" data-speed="0.7">慢速</button>
                            <button class="speed-btn ${speechManager.rate === 1.0 ? 'active' : ''}" data-speed="1.0">正常</button>
                            <button class="speed-btn ${speechManager.rate === 1.3 ? 'active' : ''}" data-speed="1.3">快速</button>
                        </div>
                    </div>
                </div>

                <div class="dictation-right">
                    <div class="input-section-wide">
                        <label class="input-label">你的答案</label>
                        <input type="text" 
                               class="input-dictation" 
                               id="word-input" 
                               placeholder="请输入完整单词"
                               autocomplete="off"
                               autofocus>
                    </div>

                    <div class="feedback-area-wide" id="feedback-area"></div>

                    <div class="action-buttons-wide">
                        <button class="btn btn-secondary btn-wide" id="btn-skip">
                            ⏭️ 跳过 <span class="btn-hotkey">Ctrl+S</span>
                        </button>
                        <button class="btn btn-secondary btn-wide" id="btn-show-answer">
                            💡 查看答案 <span class="btn-hotkey">Tab</span>
                        </button>
                        <button class="btn btn-primary btn-wide" id="btn-submit">
                            ✅ 提交 <span class="btn-hotkey">Enter</span>
                        </button>
                    </div>
                </div>
            </div>
        `;
    }

    /**
     * 获取单词数量（驼峰短语）
     */
    getWordCount(word) {
        if (word.includes(' ')) {
            return word.split(' ').length;
        }
        return 1;
    }

    /**
     * 生成填空提示
     */
    generateHint(word) {
        // 移除空格，转换为驼峰格式
        let displayWord = word;
        if (word.includes(' ')) {
            const words = word.split(' ');
            displayWord = words[0].toLowerCase() + 
                         words.slice(1).map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join('');
        }

        const chars = displayWord.split('');
        
        // 间隔提示策略：显示偶数位置的字母，隐藏奇数位置（用下划线占位）
        const hintChars = chars.map((c, i) => {
            if (i % 2 === 0) {
                // 显示的字母
                return `<span class="hint-char-visible">${c}</span>`;
            } else {
                // 缺失的字母 - 用带下划线的占位符
                return `<span class="hint-char-hidden">_</span>`;
            }
        });

        return hintChars.join('');
    }

    /**
     * 绑定事件
     */
    bindEvents() {
        // 播放按钮
        const playBtn = document.getElementById('btn-play-word');
        if (playBtn) {
            playBtn.addEventListener('click', () => {
                this.playWord();
            });
        }

        // 提交按钮
        const submitBtn = document.getElementById('btn-submit');
        if (submitBtn) {
            submitBtn.addEventListener('click', () => {
                this.submit();
            });
        }

        // 跳过按钮
        const skipBtn = document.getElementById('btn-skip');
        if (skipBtn) {
            skipBtn.addEventListener('click', () => {
                this.skip();
            });
        }

        // 查看答案按钮 🆕
        const showAnswerBtn = document.getElementById('btn-show-answer');
        if (showAnswerBtn) {
            showAnswerBtn.addEventListener('click', () => {
                this.showAnswer();
            });
        }

        // 输入框回车提交
        const input = document.getElementById('word-input');
        if (input) {
            input.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    this.submit();
                }
            });
        }

        // 语速控制
        const speedBtns = document.querySelectorAll('.speed-btn');
        speedBtns.forEach(btn => {
            btn.addEventListener('click', () => {
                const speed = parseFloat(btn.dataset.speed);
                speechManager.setRate(speed);
                speedBtns.forEach(b => b.classList.remove('active'));
                btn.classList.add('active');
            });
        });

        // 键盘快捷键
        this.setupKeyboard();
    }

    /**
     * 设置键盘快捷键
     */
    setupKeyboard() {
        const handleKey = (e) => {
            const input = document.getElementById('word-input');
            
            // Ctrl+S 跳过（在任何地方都可用，包括输入框内）
            if ((e.key === 's' || e.key === 'S') && e.ctrlKey) {
                e.preventDefault();
                if (!input?.disabled) {
                    this.skip();
                }
                return;
            }
            
            // Tab键查看答案（在任何地方都可用，包括输入框内）
            if (e.key === 'Tab') {
                e.preventDefault();
                if (!input?.disabled) {
                    this.showAnswer();
                }
                return;
            }
            
            // 如果焦点在输入框且未禁用
            if (document.activeElement === input && !input.disabled) {
                // 只处理Esc
                if (e.key === 'Escape') {
                    e.preventDefault();
                    this.exit();
                }
                return; // 其他按键正常输入
            }

            // 如果输入框已禁用（答题后），回车可以进入下一题
            if (e.key === 'Enter' && this.enableNextOnEnter) {
                e.preventDefault();
                if (this.nextTimer) {
                    clearTimeout(this.nextTimer);
                }
                this.enableNextOnEnter = false;
                this.next();
                return;
            }

            // 输入框外的快捷键
            switch(e.key) {
                case ' ':
                case 'Space':
                    e.preventDefault();
                    this.playWord();
                    break;
                case 'Enter':
                    if (!input || !input.disabled) {
                        this.submit();
                    }
                    break;
                case 'Escape':
                    this.exit();
                    break;
            }
        };

        if (this.keyboardHandler) {
            document.removeEventListener('keydown', this.keyboardHandler);
        }
        
        this.keyboardHandler = handleKey;
        document.addEventListener('keydown', handleKey);
    }

    /**
     * 播放单词
     */
    playWord() {
        const currentWord = this.words[this.currentIndex];
        if (!currentWord || !window.speechManager) return;

        const playBtn = document.getElementById('btn-play-word');
        if (playBtn) {
            playBtn.classList.add('playing');
            setTimeout(() => playBtn.classList.remove('playing'), 500);
        }

        const word = currentWord.word;
        
        // 判断播放方式
        if ((this.mode === 'camelCase' || this.mode === 'fillIn') && 
            (currentWord.type === '驼峰短语' || currentWord.pronunciation_mode === 'split')) {
            // 驼峰模式/填空模式的驼峰短语：分词播放
            const displayWord = this.formatCamelCase(word);
            speechManager.speakCamelCase(displayWord);
        } else {
            // 单词模式：完整播放
            speechManager.speak(word);
        }
    }

    /**
     * 格式化为驼峰格式
     */
    formatCamelCase(word) {
        if (word.includes(' ')) {
            const words = word.split(' ');
            return words[0].toLowerCase() + 
                   words.slice(1).map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join('');
        }
        return word;
    }

    /**
     * 提交答案
     */
    submit() {
        const input = document.getElementById('word-input');
        if (!input) return;

        const userInput = input.value.trim();
        
        if (!userInput) {
            this.showFeedback('请输入答案', 'warning');
            return;
        }

        const currentWord = this.words[this.currentIndex];
        const timeSpent = Date.now() - this.currentWordStartTime;

        // 验证答案
        const validation = this.validateAnswer(userInput, currentWord);

        // 记录结果
        this.results.push({
            word: currentWord.word,
            translation: currentWord.translation,
            userInput: userInput,
            correct: validation.correct,
            correctAnswer: validation.correctAnswer,
            timeSpent: timeSpent,
            mode: this.mode
        });

        // 显示反馈
        this.showDetailedFeedback(validation, currentWord);

        // 保存到学习历史
        this.saveToHistory(currentWord.word, validation.correct, userInput, timeSpent);

        // 如果答错，添加到错词本
        if (!validation.correct && window.wrongbookManager) {
            wrongbookManager.addWrongWord(currentWord.word, userInput, this.mode);
        }

        // 设置自动进入下一题的延迟时间
        const delay = validation.correct ? 30000 : 90000; // 正确30秒，错误1分半
        
        this.nextTimer = setTimeout(() => {
            this.next();
        }, delay);
    }

    /**
     * 验证答案
     */
    validateAnswer(userInput, currentWord) {
        const input = userInput.toLowerCase().trim();
        const correctWord = this.formatCamelCase(currentWord.word);

        if (this.mode === 'camelCase') {
            return this.validateCamelCase(input, currentWord.word, correctWord);
        } else {
            return this.validateWord(input, currentWord.word);
        }
    }

    /**
     * 验证驼峰命名
     */
    validateCamelCase(userInput, originalWord, correctCamelCase) {
        const input = userInput.trim();
        
        // 生成可接受的答案
        const words = originalWord.split(' ').map(w => w.toLowerCase());
        const camelCase = words[0] + words.slice(1).map(w => w.charAt(0).toUpperCase() + w.slice(1)).join('');
        const pascalCase = words.map(w => w.charAt(0).toUpperCase() + w.slice(1)).join('');

        // 检查是否完全正确
        if (input === camelCase) {
            return {
                correct: true,
                format: 'camelCase',
                message: '✅ 完全正确！',
                correctAnswer: camelCase
            };
        }

        if (input === pascalCase) {
            return {
                correct: true,
                format: 'PascalCase',
                message: '✅ 正确！(大驼峰命名)',
                correctAnswer: camelCase
            };
        }

        // 检查是否拼写正确但格式错误
        const lowerInput = input.toLowerCase();
        const lowerCorrect = words.join('');

        if (lowerInput === lowerCorrect) {
            return {
                correct: false,
                format: 'wrong-format',
                message: '❌ 单词拼写正确，但缺少驼峰格式',
                hint: `正确格式: ${camelCase}`,
                correctAnswer: camelCase
            };
        }

        // 完全错误
        return {
            correct: false,
            format: 'wrong',
            message: '❌ 拼写错误',
            hint: `正确答案: ${camelCase}`,
            correctAnswer: camelCase
        };
    }

    /**
     * 验证单词
     */
    validateWord(userInput, correctWord) {
        const input = userInput.toLowerCase().trim();
        const correct = correctWord.toLowerCase().trim();

        if (input === correct) {
            return {
                correct: true,
                message: '✅ 完全正确！',
                correctAnswer: correctWord
            };
        }

        return {
            correct: false,
            message: '❌ 拼写错误',
            hint: `正确答案: ${correctWord}`,
            correctAnswer: correctWord
        };
    }

    /**
     * 显示详细反馈
     */
    showDetailedFeedback(validation, currentWord) {
        const feedbackArea = document.getElementById('feedback-area');
        if (!feedbackArea) return;

        const feedbackClass = validation.correct ? 'feedback-correct' : 'feedback-wrong';
        
        // 获取用户输入（用于对比）
        const input = document.getElementById('word-input');
        const userInput = input ? input.value.trim() : '';

        // 如果答错，生成对比显示
        let comparisonHtml = '';
        if (!validation.correct && userInput && validation.correctAnswer) {
            comparisonHtml = this.generateComparisonHtml(userInput, validation.correctAnswer);
        }

        feedbackArea.innerHTML = `
            <div class="feedback ${feedbackClass} animate-fadeIn">
                <div class="feedback-message">${validation.message}</div>
                ${validation.hint ? `<div class="feedback-hint">${validation.hint}</div>` : ''}
                ${comparisonHtml}
                <div class="feedback-details">
                    <div class="detail-item">
                        <span class="detail-label">中文:</span>
                        <span class="detail-value">${currentWord.translation || '无'}</span>
                    </div>
                    ${validation.format ? `
                        <div class="detail-item">
                            <span class="detail-label">命名:</span>
                            <span class="detail-value">${this.getFormatName(validation.format)}</span>
                        </div>
                    ` : ''}
                </div>
                <button class="btn-play-feedback" onclick="dictationManager.playWord()">
                    🔊 再听一次
                </button>
                <div class="next-hint">
                    按 <kbd>Enter</kbd> 继续下一题
                </div>
            </div>
        `;

        // 禁用输入
        if (input) {
            input.disabled = true;
        }

        // 绑定回车键进入下一题
        this.enableNextOnEnter = true;
    }

    /**
     * 生成对比显示HTML（标出错误部分）
     */
    generateComparisonHtml(userInput, correctAnswer) {
        const comparison = this.compareStrings(userInput, correctAnswer);
        
        return `
            <div class="comparison-container-compact">
                <div class="comparison-text">
                    <span class="comparison-label-inline">你的:</span>
                    <span class="comparison-value user-answer-display">${comparison.userDisplay}</span>
                </div>
                <div class="comparison-text">
                    <span class="comparison-label-inline">正确:</span>
                    <span class="comparison-value correct-answer-display">${comparison.correctDisplay}</span>
                </div>
            </div>
        `;
    }

    /**
     * 对比两个字符串，标出差异
     */
    compareStrings(user, correct) {
        const userLower = user.toLowerCase();
        const correctLower = correct.toLowerCase();
        
        let userDisplay = '';
        let correctDisplay = '';
        
        const maxLen = Math.max(user.length, correct.length);
        
        for (let i = 0; i < maxLen; i++) {
            const userChar = user[i] || '';
            const correctChar = correct[i] || '';
            const userCharLower = userLower[i] || '';
            const correctCharLower = correctLower[i] || '';
            
            if (userChar === correctChar) {
                // 完全相同（包括大小写）
                userDisplay += `<span class="char-correct">${userChar}</span>`;
                correctDisplay += `<span class="char-same">${correctChar}</span>`;
            } else if (userCharLower === correctCharLower) {
                // 字母相同但大小写不同
                userDisplay += `<span class="char-case-wrong">${userChar}</span>`;
                correctDisplay += `<span class="char-case-diff">${correctChar}</span>`;
            } else {
                // 字母错误
                if (userChar) {
                    userDisplay += `<span class="char-wrong">${userChar}</span>`;
                }
                if (correctChar) {
                    correctDisplay += `<span class="char-missing">${correctChar}</span>`;
                }
            }
        }
        
        return {
            userDisplay: userDisplay || user,
            correctDisplay: correctDisplay || correct
        };
    }

    /**
     * 获取格式名称
     */
    getFormatName(format) {
        const names = {
            'camelCase': '小驼峰 (camelCase)',
            'PascalCase': '大驼峰 (PascalCase)',
            'wrong-format': '格式错误',
            'wrong': '拼写错误'
        };
        return names[format] || format;
    }

    /**
     * 显示简单反馈
     */
    showFeedback(message, type = 'info') {
        const feedbackArea = document.getElementById('feedback-area');
        if (!feedbackArea) return;

        const className = `feedback-${type}`;
        feedbackArea.innerHTML = `
            <div class="feedback ${className}">
                ${message}
            </div>
        `;
    }

    /**
     * 查看答案（不会的时候） 🆕
     */
    showAnswer() {
        const currentWord = this.words[this.currentIndex];
        const feedbackArea = document.getElementById('feedback-area');
        if (!feedbackArea) return;

        const correctAnswer = this.formatCamelCase(currentWord.word);

        feedbackArea.innerHTML = `
            <div class="feedback feedback-info-compact animate-fadeIn">
                <div class="answer-header">💡 正确答案</div>
                <div class="answer-display-compact">
                    <div class="answer-word-compact">${correctAnswer}</div>
                    <div class="answer-translation-compact">${currentWord.translation || '无释义'}</div>
                </div>
                <div class="answer-details-compact">
                    ${currentWord.type ? `<span class="detail-tag">📝 ${currentWord.type}</span>` : ''}
                    ${currentWord.category ? `<span class="detail-tag">🏷️ ${currentWord.category}</span>` : ''}
                </div>
                ${currentWord.example_code ? `
                    <div class="code-example-compact">
                        <code>${this.escapeHtml(currentWord.example_code)}</code>
                    </div>
                ` : ''}
                <button class="btn-play-feedback-compact" onclick="dictationManager.playWord()">
                    🔊 再听一次
                </button>
                <div class="view-answer-hint-compact">
                    💡 继续输入尝试，或点击跳过
                </div>
            </div>
        `;

        // 输入框聚焦，让用户可以继续尝试输入
        const input = document.getElementById('word-input');
        if (input) {
            input.focus();
        }
    }

    /**
     * 转义HTML
     */
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    /**
     * 跳过当前单词
     */
    skip() {
        const currentWord = this.words[this.currentIndex];
        
        this.results.push({
            word: currentWord.word,
            translation: currentWord.translation,
            userInput: '',
            correct: false,
            skipped: true,
            timeSpent: Date.now() - this.currentWordStartTime,
            mode: this.mode
        });

        this.next();
    }

    /**
     * 下一题
     */
    next() {
        this.currentIndex++;
        if (this.currentIndex < this.words.length) {
            this.render();
            
            // 自动聚焦到输入框
            setTimeout(() => {
                const input = document.getElementById('word-input');
                if (input) {
                    input.focus();
                }
            }, 400); // 等待动画和自动播放
        } else {
            this.finish();
        }
    }

    /**
     * 更新进度
     */
    updateProgress() {
        document.getElementById('dictation-current').textContent = this.currentIndex + 1;
        document.getElementById('dictation-total').textContent = this.words.length;
        
        // 计算正确率
        const correctCount = this.results.filter(r => r.correct).length;
        const totalAnswered = this.results.length;
        const accuracy = totalAnswered > 0 ? Math.round((correctCount / totalAnswered) * 100) : 0;
        
        document.getElementById('dictation-accuracy').textContent = accuracy + '%';
    }

    /**
     * 保存到学习历史
     */
    saveToHistory(word, correct, userInput, timeSpent) {
        const learningHistory = storageManager.get(storageManager.keys.LEARNING_HISTORY) || {};
        
        if (!learningHistory[word]) {
            learningHistory[word] = {
                attempts: 0,
                correct: 0,
                wrong: 0,
                accuracy: 0,
                lastDictation: null,
                history: []
            };
        }

        const data = learningHistory[word];
        data.attempts++;
        
        if (correct) {
            data.correct++;
        } else {
            data.wrong++;
        }
        
        data.accuracy = data.correct / data.attempts;
        data.lastDictation = new Date().toISOString();
        
        data.history.push({
            date: new Date().toISOString(),
            correct: correct,
            mode: this.mode,
            userInput: userInput,
            timeSpent: timeSpent
        });

        storageManager.set(storageManager.keys.LEARNING_HISTORY, learningHistory);
    }

    /**
     * 完成听写
     */
    finish() {
        console.log('听写完成', this.results);
        
        // 移除键盘监听
        if (this.keyboardHandler) {
            document.removeEventListener('keydown', this.keyboardHandler);
            this.keyboardHandler = null;
        }

        // 计算统计
        const stats = this.calculateStats();

        // 保存会话
        this.saveSession(stats);

        // 显示结果
        this.renderResults(stats);
    }

    /**
     * 计算统计数据
     */
    calculateStats() {
        const total = this.results.length;
        const correct = this.results.filter(r => r.correct).length;
        const wrong = this.results.filter(r => !r.correct && !r.skipped).length;
        const skipped = this.results.filter(r => r.skipped).length;
        
        const accuracy = total > 0 ? Math.round((correct / total) * 100) : 0;
        const totalTime = this.results.reduce((sum, r) => sum + r.timeSpent, 0);
        const avgTime = total > 0 ? Math.round(totalTime / total / 1000) : 0;

        return {
            total,
            correct,
            wrong,
            skipped,
            accuracy,
            duration: Date.now() - this.sessionStartTime,
            avgTime
        };
    }

    /**
     * 保存会话
     */
    saveSession(stats) {
        const sessions = storageManager.get(storageManager.keys.SESSIONS) || [];
        
        // 提取单词本ID
        const wordbookIds = [...new Set(this.words.map(w => w.wordbookId).filter(id => id))];
        
        const session = {
            sessionId: `dictation-${Date.now()}`,
            mode: `dictation-${this.mode}`,
            startTime: new Date(this.sessionStartTime).toISOString(),
            endTime: new Date().toISOString(),
            duration: stats.duration,
            totalWords: stats.total,
            correctWords: stats.correct,
            wrongWords: stats.wrong,
            accuracy: stats.accuracy / 100,
            wordbookIds: wordbookIds,
            results: this.results
        };

        sessions.push(session);
        storageManager.set(storageManager.keys.SESSIONS, sessions);

        // 更新相关单词本的统计数据
        if (window.wordbookManager) {
            wordbookIds.forEach(id => {
                wordbookManager.updateWordbookStats(id);
            });
        }
    }

    /**
     * 渲染结果
     */
    renderResults(stats) {
        const container = document.querySelector('.dictation-container');
        if (!container) return;

        const duration = Math.floor(stats.duration / 1000);
        const minutes = Math.floor(duration / 60);
        const seconds = duration % 60;

        const wrongWords = this.results.filter(r => !r.correct);

        container.innerHTML = `
            <div class="results-container animate-fadeIn">
                <div class="results-header">
                    <h2>🎉 听写完成！</h2>
                </div>

                <div class="results-summary">
                    <div class="summary-card">
                        <div class="summary-label">总计</div>
                        <div class="summary-value">${stats.total}</div>
                    </div>
                    <div class="summary-card card-success">
                        <div class="summary-label">✅ 正确</div>
                        <div class="summary-value">${stats.correct}</div>
                        <div class="summary-percent">${stats.accuracy}%</div>
                    </div>
                    <div class="summary-card card-error">
                        <div class="summary-label">❌ 错误</div>
                        <div class="summary-value">${stats.wrong}</div>
                    </div>
                    ${stats.skipped > 0 ? `
                    <div class="summary-card">
                        <div class="summary-label">⏭️ 跳过</div>
                        <div class="summary-value">${stats.skipped}</div>
                    </div>
                    ` : ''}
                </div>

                <div class="results-meta">
                    <span>⏱️ 用时: ${minutes}分${seconds}秒</span>
                    <span>📈 平均: ${stats.avgTime}秒/词</span>
                    <span>📅 ${new Date().toLocaleTimeString()}</span>
                </div>

                ${wrongWords.length > 0 ? `
                    <div class="review-section">
                        <h3>❌ 错误单词</h3>
                        <div class="wrong-words-review">
                            ${wrongWords.map(r => `
                                <div class="wrong-word-item">
                                    <div class="wrong-word-main">
                                        <span class="word-correct">${r.correctAnswer}</span>
                                        <span class="word-translation">${r.translation}</span>
                                    </div>
                                    ${!r.skipped ? `
                                        <div class="wrong-word-detail">
                                            <span class="user-answer">你的答案: ${r.userInput || '(空)'}</span>
                                        </div>
                                    ` : `
                                        <div class="wrong-word-detail">
                                            <span class="skipped-tag">已跳过</span>
                                        </div>
                                    `}
                                </div>
                            `).join('')}
                        </div>
                    </div>
                ` : `
                    <div class="perfect-message">
                        <div class="perfect-icon">🌟</div>
                        <h3>完美！全部正确</h3>
                    </div>
                `}

                <div class="results-actions">
                    ${wrongWords.length > 0 ? `
                        <button class="btn btn-primary" id="btn-review-wrong">
                            复习错词 (${wrongWords.length}个)
                        </button>
                    ` : ''}
                    <button class="btn btn-secondary" id="btn-back-home">返回首页</button>
                </div>
            </div>
        `;

        // 绑定按钮
        const reviewBtn = document.getElementById('btn-review-wrong');
        if (reviewBtn) {
            reviewBtn.addEventListener('click', () => {
                const reviewWords = wrongWords.map(r => {
                    return this.words.find(w => w.word === r.word);
                }).filter(w => w);
                
                this.start(reviewWords, this.mode);
            });
        }

        const backBtn = document.getElementById('btn-back-home');
        if (backBtn) {
            backBtn.addEventListener('click', () => {
                if (window.app) {
                    app.navigateTo('home');
                    // 刷新首页，更新进度
                    setTimeout(() => {
                        app.updateHomePage();
                    }, 100);
                }
            });
        }
    }

    /**
     * 退出
     */
    exit() {
        if (confirm('确定要退出吗？当前进度将不会保存。')) {
            if (this.keyboardHandler) {
                document.removeEventListener('keydown', this.keyboardHandler);
                this.keyboardHandler = null;
            }
            
            if (window.app) {
                app.navigateTo('home');
            }
        }
    }
}

// 全局实例
const dictationManager = new DictationManager();
window.dictationManager = dictationManager;
